/*
 * The contents of this file are subject to the Mozilla Public License
 * Version 1.1 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations
 * under the License.
 * 
 * The Original Code is iSQL-Viewer, A Mutli-Platform Database Tool.
 *
 * The Initial Developer of the Original Code is iSQL-Viewer, A Mutli-Platform Database Tool.
 * Portions created by Mark A. Kobold are Copyright (C) 2000-2007. All Rights Reserved.
 *
 * Contributor(s): 
 *  Mark A. Kobold [mkobold <at> isqlviewer <dot> com].
 *  
 * If you didn't download this code from the following link, you should check
 * if you aren't using an obsolete version: http://www.isqlviewer.com
 */
package org.isqlviewer.ui;

import java.awt.AWTEvent;
import java.awt.Frame;
import java.awt.Rectangle;
import java.awt.event.WindowEvent;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JPanel;

import org.apache.log4j.BasicConfigurator;
import org.isqlviewer.swing.SwingUtilities;
import org.isqlviewer.swing.WizardPanel;
import org.isqlviewer.swing.action.SwingEventManager;
import org.isqlviewer.util.IsqlToolkit;

/**
 * @author Markus A. Kobold &lt;mkobold at sprintpcs dot com&gt;
 * @version 1.0
 */
public class ApplicationFrame extends JFrame {

    private static final long serialVersionUID = -3603727788974494075L;
    private static final String WINDOW_ID = "main-window";

    private JMenuBar menuBar = new JMenuBar();
    private WizardPanel contentPanel = new WizardPanel();
    private ApplicationView defaultView = null;
    private SwingEventManager swingEventManager = new SwingEventManager();
    private Preferences applicationPreferences = null;

    public ApplicationFrame() {

        super("iSQL-Viewer v.3.0.0");
        Preferences userRoot = Preferences.userRoot();
        applicationPreferences = userRoot.node(IsqlToolkit.getRootPreferencesNode());
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        enableEvents(AWTEvent.KEY_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK);
        swingEventManager.start();
        BasicConfigurator.configure();
        try {
            initializeUI();
        } catch (Throwable t) {
            throw new RuntimeException(t);
        }
        if (!SwingUtilities.isMacOS()) {
            ImageIcon iconImage = (ImageIcon) SwingUtilities.loadIconResource("application", 128);
            setIconImage(iconImage.getImage());
        }
    }

    @Override
    protected void processWindowEvent(WindowEvent e) {

        switch (e.getID()) {
            case WindowEvent.WINDOW_OPENED :
                retrieveWindowPrefs(WINDOW_ID, this);
                defaultView.initializeView();
                String jre = System.getProperty("java.specification.version");
                if ("1.5".equals(jre)) {
                    validateTree();
                }
                break;
            case WindowEvent.WINDOW_CLOSING :
                storeWindowPrefs(WINDOW_ID, this);
                defaultView.disposeView(applicationPreferences);
                try {
                    applicationPreferences.sync();
                } catch (BackingStoreException error) {
                    error.printStackTrace(System.err);
                }
                break;
        }
        super.processWindowEvent(e);
    }

    private synchronized void initializeUI() throws Exception {

        setContentPane(contentPanel);
        setJMenuBar(menuBar);
        JdbcWorkbench workbench = new JdbcWorkbench();
        JPanel applicationView = new JPanel();
        workbench.doLayout(applicationView, applicationPreferences, swingEventManager);
        workbench.configureMenubar(menuBar);
        contentPanel.add("root-view", applicationView);
        pack();
        defaultView = workbench;
    }

    public void storeWindowPrefs(String name, Frame window) {

        Preferences windowsRoot = applicationPreferences.node("windows");
        Preferences windowPrefs = windowsRoot.node(name);
        Rectangle rect = window.getBounds();
        windowPrefs.putInt("x", rect.x);
        windowPrefs.putInt("y", rect.y);
        windowPrefs.putInt("width", rect.width);
        windowPrefs.putInt("height", rect.height);
        windowPrefs.putBoolean("maximized", (window.getExtendedState() == Frame.MAXIMIZED_BOTH));
    }

    public boolean retrieveWindowPrefs(String name, Frame window) {

        Preferences windowRoot = applicationPreferences.node("windows");
        try {
            if (!windowRoot.nodeExists(name)) {
                window.setBounds(new Rectangle(0, 0, 800, 600));
                SwingUtilities.centerFrameOnScreen(this);
                return false;
            }
        } catch (BackingStoreException e) {
            return false;
        }
        Preferences windowPrefs = windowRoot.node(name);
        int x, y, width, height;
        x = windowPrefs.getInt("x", 0);
        y = windowPrefs.getInt("y", 0);
        width = windowPrefs.getInt("width", 800);
        height = windowPrefs.getInt("height", 600);
        window.setBounds(new Rectangle(x, y, width, height));
        if (windowPrefs.getBoolean("maximized", false)) {
            window.setExtendedState(Frame.MAXIMIZED_BOTH);
        } else if (x == 0 && y == 0) {
            SwingUtilities.centerFrameOnScreen(this);
        }
        return true;
    }

    public SwingEventManager getSwingEventManager() {

        return swingEventManager;
    }
}